window.onload = function (){
    const homePage = {
        init(){
            axios.defaults.baseURL = 'http://localhost:3000';
            homePage.fun.render();
            document.addEventListener('click',homePage.fun.handleDeleteMovieClick,false);
        },
    fun:{
        render(){
            axios.get('http://localhost:3000/movies')
            .then(function (reponse){
                let movies = reponse.data,str = '';
                movies.forEach(movie =>{
                    let star = '★★★★★☆☆☆☆☆';
                    let rate = Math.round(movie.score/2);
                    str +=`<li class="movieBox">
                    <i class="delMovie" data-movieId="${movie.id}">x</i>
                    <div class="mPost">
                        <img src="${movie.post}",alt="${movie.title}">
                    </div>
                    <div class="mTitle">${movie.title}</div>
                    <div class="mScore">${star.slice(5-rate,10-rate) + movie.score} 分</div>
                </li>`
                })
                let moviesRow = document.getElementById('moviesRow');
                moviesRow.innerHTML = str;  
            })
            .catch(function(error){
                console.log(error);
            });
        },
        handleDeleteMovieClick(e){
            let movieId = e.target.getAttribute("data-movieId");
            if(movieId){
                let confirmDel = confirm("确认删除？");
                if(confirmDel) homePage.fun.deleteMovieById(movieId);
                else return "eee";
            }else{
                return "aaa";
            }
        },
        deleteMovieById(movieId){
            axios.delete(`http://localhost:3000/movies/${movieId}`)
            .then(function (reponse) {
                if(reponse.status === 200){
                        console.log("删除成功！");
                        homePage.init();
                }
            })
            .catch(function(error){
                console.log(error);
            });
        }
    }       
    }
    homePage.init();
}
